package com.komorebi.friends.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.komorebi.friends.common.ErrorCode;
import com.komorebi.friends.common.ResultUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

/**
 * 最后并没有使用，因为打算和登录验证一样，写在业务层，通过抛异常的方法
 */

//@Component
//@Order(1)
public class VerificationCodeFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 拦截登录:如果不是登录则放行
        if(!"POST".equals(request.getMethod()) || !"/user/login".equals(request.getServletPath())){
            filterChain.doFilter(request,response);
        }
        else {
            String requestCode = (String) request.getSession().getAttribute("verify_code");
            String code = request.getParameter("code");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            try{
                if(!code.toLowerCase().equals(requestCode.toLowerCase())){
                    writer.write(new ObjectMapper().writeValueAsString(ResultUtils.error(ErrorCode.PARAMS_ERROR,"验证码错误")));
                    //return; // finally 会在 return 之后执行
                }else{
                    filterChain.doFilter(request,response);
                }
            } catch (NullPointerException e){
                writer.write(new ObjectMapper().writeValueAsString(ResultUtils.error(ErrorCode.PARAMS_ERROR,"请求异常，请重新请求！")));
            } finally {
                writer.flush();
                writer.close();
            }
        }
    }
}
